# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
        def dfs(root1, root2):
            if root1 is None or root2 is None:
                return root1 == root2
            if root1.val != root2.val:
                return False
            root1_left_val = None if root1.left is None else root1.left.val
            root1_right_val = None if root1.right is None else root1.right.val
            root2_left_val = None if root2.left is None else root2.left.val
            root2_right_val = None if root2.right is None else root2.right.val
            if root1_left_val != root2_left_val and root1_right_val != root2_right_val:
                if root1_left_val != root2_right_val and root1_right_val != root2_left_val:
                    return False
                root2_left = root2.left
                root2.left = root2.right
                root2.right = root2_left
            return dfs(root1.left, root2.left) and dfs(root1.right,
                                                       root2.right)

        return dfs(root1, root2)
